<?php

class SiteController extends Controller {

    public $layout = "column2";

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('*'),
                'users' => array('*'),
            ),
        );
    }

    /**
     * 首页
     */
    public function actionIndex() {
        //热门产品
        $hot_category = SubsiteCategory::model()->getHotCategory();
        //推荐新闻
        $news = Information::model()->getIndexNews();
        $this->render('index', array(
            'hot_category' => $hot_category,
            'news' => $news,
        ));
    }

    /**
     * 会员注册
     */
    public function actionSign() {
        $cookie = Yii::app()->request->getCookies();
        $model = isset($cookie['member_uid']) ? WebCustomers::model()->findByPk($cookie['member_uid']->value) : new WebCustomers();
        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            if ($model->password) {
                $model->salt = $model->generationSalt();
                $model->password = $model->generationPassword($model->password, $model->salt);
            }
            if ($model->save()) {
                $message = '<span class="highshow">Sign Success!</span>';
                $loginModel = new LoginForm;
                $loginModel->username = $_POST['User']['mail'];
                $loginModel->password = $_POST['User']['password'];
                $loginModel->validate();
                $loginModel->login();
            } else {
                $message = '<span class="highshow">Sign Faild!</span>';
            }
            $this->render('sign_success', array(
                'message' => $message,
            ));
            Yii::app()->end();
        }
        $this->render('sign', array(
            'member' => $model,
        ));
    }

    /**
     * 改变用户密码
     */
    public function actionChangePassword() {
        if (isset($_GET['f'])) {
            /**
             * 验证邮件找回密码
             */
            $forgetKey = $_GET['f'];
            $email = Yii::app()->cache->get($forgetKey);
            if ($email == false) {
                $this->redirect($this->createUrl('/site'));
                Yii::app()->end();
            }
            $member = WebCustomers::model()->checkMemberByMail($email);
            $_SESSION['forget_uid'] = $member->id;
        } else if (Yii::app()->user->isGuest) {
            $this->redirect($this->createUrl('/site'));
            Yii::app()->end();
        }
        if (isset($_POST['User'])) {
            $newPass = $_POST['User']['newPass'];
            if (isset($_SESSION['forget_uid'])) {
                $oldPass = '';
                $uid = $_SESSION['forget_uid'];
                unset($_SESSION['forget_uid']);
            } else {
                $oldPass = $_POST['User']['oldPass'];
                $uid = Yii::app()->request->cookies['member_uid']->value;
            }
            $message = WebCustomers::model()->CustomersUpdatePass($uid, $oldPass, $newPass);
            $this->render('sign_success', array(
                'message' => $message,
            ));
            Yii::app()->end();
        }
        $this->render('password');
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {
//        if (!Yii::app()->user->isGuest) {
//            $this->redirect(Yii::app()->user->returnUrl);
//        }
        $model = new LoginForm;

// if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
// collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login()) {
                $rUrl = $this->createUrl('order/cart');
                $this->redirect($rUrl);
            }
        }
// display the login form
        $this->render('login', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $uid = new CHttpCookie('member_uid', null);
        $uid->expire = -3600;
        Yii::app()->request->cookies['member_uid'] = $uid;
        $member_level = new CHttpCookie('member_level', null);
        $member_level->expire = -3600;
        Yii::app()->request->cookies['member_level'] = $member_level;
        $this->redirect(Yii::app()->homeUrl);
    }

    /**
     * 发送邮件
     */
    public function actionSendMail() {
        echo 'Send mail';
        $email_address = 'hanbiji@163.com';
        $subject = 'test';
        $mailInfo = 'test';
        //发送邮件
        Yii::import('application.ext.*');
        require_once('mailer/class.phpmailer.php');
        $mail = new PHPMailer(true); //the true param means it will throw exceptions on errors, which we need to catch
         echo 'Send mail';

        $mail->IsSMTP(); // telling the class to use SMTP

        try {
            $mail->Host = "mail.google.com"; // SMTP server
            $mail->SMTPDebug = 0;                     // enables SMTP debug information (for testing)
            $mail->SMTPAuth = true;                  // enable SMTP authentication
            $mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
            $mail->Host = "smtp.gmail.com";      // sets GMAIL as the SMTP server
            $mail->Port = 465;                   // set the SMTP port for the GMAIL server
            $mail->Username = "flowf168@gmail.com";  // GMAIL username
            $mail->Password = "rei0Foh{y";            // GMAIL password
            $mail->AddAddress($email_address);
            $mail->SetFrom('flowf168@gmail.com', 'Usfine webmaster');
            $mail->Subject = $subject;
            $mail->CharSet = 'utf-8';
            $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
            $mail->MsgHTML($mailInfo);

            $mail->Send();
            $message = 'OK';
        } catch (phpmailerException $e) {
            $message = $e->errorMessage(); //Pretty error messages from PHPMailer
        } catch (Exception $e) {
            $message = $e->getMessage(); //Boring error messages from anything else!
        }
        echo $message;
    }

    /**
     * 错误显示页面
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

}
